local redis_client = require "lib.redis"
local redis = redis_client:new()
local args = ngx.req.get_uri_args()

if nil == args.vote_id then
    ngx.say('{"code":10000,"message":"vote_id不能为空"}')
    return
end

local vote_id = args.vote_id

-- 根据投票数查出id和对应的票数
local rank, err = redis:zrevrangebyscore('ranking:'..vote_id, '+inf', 0, 'WITHSCORES', 'LIMIT', 0, 20)

if nil == rank then
    ngx.log(ngx.ERR, 'connect redis faild:', err)
    ngx.say('{"code":10000,"message":"无效的投票项目"}')
    return
end

local item_keys, scores = {}, {}

-- 将id和票数分别组装，并将id组合成取item得key
for i, value in pairs(rank) do
    if i % 2 == 0 then
        --票数
        table.insert(scores, value)
    else
        --id
        table.insert(item_keys, 'item:'..vote_id..":"..value)
    end
end


local ranking, err = redis:mget(unpack(item_keys))


local items = {}


for of, item in ipairs(ranking) do
    if item == ngx.null then
        table.remove(scores, of)
    else
        table.insert(items, item)
    end
end

ngx.say('{"items":[', table.concat(items, ','), '],"scores":[', table.concat(scores, ','), '],"code":200}')

